import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders


def generate_html_report(report_dir, report_filename, test_cases):
    """
    生成HTML报告文件。

    :param report_dir: 报告文件存放的目录
    :param report_filename: 报告文件名
    :param test_cases: 测试用例数据列表
    :return: 完整的报告文件路径
    """
    report_path = os.path.join(report_dir, report_filename)

    # 计算通过率
    total_tests = len(test_cases)
    passed_tests = sum(1 for case in test_cases if case["status"] == "Passed")
    # passed_tests = sum(1 for case in test_cases if case["状态"] == "Passed")
    pass_rate = (passed_tests / total_tests) * 100 if total_tests > 0 else 0

    # 创建HTML内容
    html_content = f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>自动化测试报告</title>
        <style>
            body {{
                font-family: Arial, sans-serif;
                margin: 20px;
            }}
            h1 {{
                color: #333;
            }}
            p {{
                line-height: 1.6;
            }}
            .section {{
                margin-bottom: 20px;
                border: 1px solid black;
                padding: 10px;
            }}
            table {{
                width: 100%;
                border-collapse: collapse;
                margin-top: 20px;
                border: 1px solid black;
            }}
            th, td {{
                border: 1px solid black;
                padding: 8px;
                text-align: left;
            }}
            th {{
                background-color: #f2f2f2;
            }}
            .pass-rate {{
                font-size: 1.2em;
                font-weight: bold;
                color: {'green' if pass_rate >= 70 else 'red'};
            }}
        </style>
    </head>
    <body>
        <div class="section">
            <h1>自动化测试报告</h1>
            <p>这是食堂产品线的用例执行结果报告</p>
        </div>
        <div class="section">
            <h2>用例概述</h2>
            <ul>
                <li>总共执行用例数量: {total_tests}</li>
                <li>通过的用例数量: {passed_tests}</li>
                <li>通过率: <span class="pass-rate">{pass_rate:.2f}%</span></li>
            </ul>
        </div>
        <div class="section">
            <h2>用例详情列表</h2>
            <table>
                <thead>
                    <tr>
                        <th>用例ID</th>
                        <th>用例功能描述</th>
                        <th>通过/失败</th>
                        <th>备注</th>
                    </tr>
                </thead>
                <tbody>
                    {''.join(f"<tr><td>{case['id']}</td><td>{case['description']}</td><td>{case['status']}</td><td>{case.get('comment', '')}</td></tr>" for case in test_cases)}
                </tbody>
            </table>
        </div>
    </body>
    </html>
    """

    # 写入HTML文件
    with open(report_path, 'w', encoding='utf-8') as file:
        file.write(html_content)

    return report_path


def send_email_with_attachment(file_path, smtp_server, smtp_port, email_from, email_to, email_subject, email_username,
                               email_password):
    """
    发送带有附件的电子邮件。

    :param file_path: 要作为附件发送的文件路径
    :param smtp_server: SMTP 服务器地址（例如 'smtp.example.com'）
    :param smtp_port: SMTP 服务器端口（通常为 587）
    :param email_from: 发件人邮箱地址
    :param email_to: 收件人邮箱地址
    :param email_subject: 邮件主题
    :param email_username: 登录 SMTP 服务器的用户名（通常是发件人邮箱地址）
    :param email_password: 登录 SMTP 服务器的密码或授权码
    """

    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = email_from
    msg['To'] = email_to
    msg['Subject'] = email_subject

    # 将HTML内容添加到邮件正文中
    with open(file_path, 'r', encoding='utf-8') as file:
        html_body = file.read()

    # 【傻叉！！！】打印 HTML 内容
    print("HTML Content:\n", html_body)

    msg.attach(MIMEText(html_body, 'html'))

    # 添加附件
    try:
        with open(file_path, "rb") as attachment:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(attachment.read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', f"attachment; filename= {os.path.basename(file_path)}")
            msg.attach(part)
            print(f"Attached file: {file_path}")
    except FileNotFoundError:
        print(f"File {file_path} not found.")
        return

    # 发送邮件
    server = None
    try:
        print(f"Connecting to {smtp_server} on port {smtp_port}...")
        server = smtplib.SMTP(smtp_server, smtp_port)
        print("Connected to SMTP server.")

        server.starttls()

        print(f"Logging in as {email_username}...")
        server.login(email_username, email_password)
        print("Logged in successfully.")

        print(f"Sending email to {email_to}...")
        text = msg.as_string()
        server.sendmail(email_from, email_to, text)
        print("Email sent successfully!")

    except smtplib.SMTPAuthenticationError:
        print("Failed to log in: Authentication error.")
    except smtplib.SMTPServerDisconnected:
        print("The server unexpectedly disconnected.")
    except smtplib.SMTPException as e:
        print(f"SMTP error occurred: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

    finally:
        if server is not None:
            server.quit()
            print("Connection closed.")

    print("okokok！！！！！")  # 邮件发送成功后打印确认信息